var express 		= require('express');
var mysql   		= require('mysql');
var config  		= require('../config.json');
var sqlconfig 		= config.mysql;
var router  		= express.Router();
var pool    		= mysql.createPool(sqlconfig);

/*
  Name: data
  Args:
	data:data to be return
	res :response to write data
  Return : 
	Valid String for Client to use
  Description：
	  Return the valid  Data String to client if there is no error
*/

function data(data,res)
{
	console.log("LOG:RESPONSE:"+JSON.stringify(data));
	return res.end(JSON.stringify({err:0,response:data}));
}

/*
  Name: error
  Args:
	res:response to write err
	err:error message to return
	errcode: description of an error
  Return : 
	Valid String for Client to use
  Description：
	Return the error message to the client 
*/

function error(err,errcode,res)
{
	//console.log("LOG:ERROR:"+errcode);
	return res.end(JSON.stringify({err : err,errcode : errcode}));
}

/*
  Name: BeforeAspect 
  Args: 
	request:Object
  Return: 
	data return from this aspect
  Description:
	preprocessor
*/

function BeforeAspect(request)
{
	
	console.log("LOG:REQUEST:"+JSON.stringify(request));
	return request;
}

/*
  Name:Student_Login[I] 
  Args: 
	req:
		JSON :[ args] arguments of this query
			stu_number:Student_number
			stu_password:Student password	
	res: response to write data/error
	next:
  Return: 
  	None
  Description:
	Interface for student to login
*/

function Student_Login(req,res,next)
{
	var query = "select * from student where stu_number = ? and stu_password = ?;"
	try{
		var args = BeforeAspect(req.body);
		var query_args = [];
		if(typeof(args) != 'object' || !args['stu_number'] || !args['stu_password'])
		{
			error(401,"Invalid Argument",res);
			return
		}

		query_args.push(args['stu_number']);
		query_args.push(args['stu_password']);

		pool.query(query,query_args,
		function(err,rows,fileds)
		{
			if(err)
			{
				error(500,err,res);
				return;
			}
			if(rows.length == 1)
			{
				req.session.user_type = "STUDENT";
				req.session.user   = rows[0];
				error(0,"Sucess",res);
				return;
			}
			else
			{
				error(201,"Wrong account or password",res);
			}
			return;
		});
	}
	catch(err)
	{
		error( -1 ,err,res);
	}
	return;
}

/*
  Name:Teacher_Login[I] 
  Args: 
	req:
		JSON :[ args] arguments of this query
			teacher_number:Teacher number
			teacher_password:Teacher password	
	res: response to write data/error
	next:
  Return: 
  	None
  Description:
	Interface for Teacher to login
*/

function Teacher_Login(req,res,next)
{
	var query = "select * from teacher where teacher_number = ? and teacher_password = ?;"
	try{
		
		var args = BeforeAspect(req.body);
		var query_args = [];
		if(typeof(args) != 'object' || !args['teacher_number'] || !args['teacher_password'])
		{
			error(401,"Invalid Argument",res);
			return
		}
		query_args.push(args['teacher_number']);
		query_args.push(args['teacher_password']);
		pool.query(query,query_args,
		function(err,rows,fileds)
		{
			if(err)
			{
				error(500,err,res);
				return;
			}
			if(rows.length == 1)
			{
				req.session.user_type = "TEACHER";
				req.session.user   = rows[0];
				error(0,"Success",res);
				return;
			}
			else
			{
				error(201,"Wrong account or password",res);
			}
			return;
		});
	}
	catch(err)
	{
		error( -1 ,err,res);
	}
	return;
}

/*
  Name:Parent_Login[I] 
  Args: 
	req:
		JSON :[ args] arguments of this query
			stu_number:Student_id
			parent_password:parent password	
	res: response to write data/error
	next:
  Return: 
  	None
  Description:
	Interface for parent to login
*/

function Parent_Login(req,res,next)
{
	var query = "SELECT * FROM (SELECT * from student WHERE stu_number = ? ) stu LEFT JOIN (SELECT * FROM parent where parent_password = ? ) p ON stu.parent_id = p.parent_id where stu_number = ? and parent_password = ?;"
	try{
		var args = BeforeAspect(req.body);	
		var query_args = [];

		if(typeof(args) != 'object' || !args['stu_number'] || !args['parent_password'])
		{
			error(401,"Invalid Argument",res);
			return
		}
		
		query_args.push(args['stu_number']);
		query_args.push(args['parent_password']);

		query_args.push(args['stu_number']);
		query_args.push(args['parent_password']);
		
		pool.query(query,query_args,
		function(err,rows,fileds)
		{
			if(err)
			{
				error(500,err,res);
				return;
			}
			if(rows.length == 1)
			{
				req.session.user_type = "PARENT";
				req.session.user   = rows[0];
				error(0,"Success",res);
				return;
			}
			else
			{
				error(201,"Wrong account or password",res);
			}
			return;
		});
	}
	catch(err)
	{
		error( -1 ,err,res);
	}
	return;
}

//Register '/' GET router
router.get('/', function(req, res, next) 
{
  data({},res);
});

//Register all routers 
var functions = {	"/student/" : Student_Login
			,"/teacher/": Teacher_Login
			,"/parent/" : Parent_Login}

for(var i in functions) 
{
	console.log("FUNCTION_LOADED(login):"+i);
	router.post(i, functions[i]);
}

module.exports = router;
